package com.longy.nio;

import com.sun.org.apache.bcel.internal.generic.Select;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;

public class TestNonBlockingNIO {
    @Test
    public void client() throws Exception {
        //1.获取通道
        SocketChannel clientChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        //2.设置非阻塞状态
        clientChannel.configureBlocking(false);
        //3.分配缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //4.发送数据给服务端
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String next = scan.next();
            buf.put((new Date().toString() + "\n" + next).getBytes());
            System.out.println("------------------" + (new Date().toString() + "\n" + next));
//            buf.put((new Date().toString()).getBytes());
            buf.flip();
            clientChannel.write(buf);
            buf.clear();
        }
        //5.关闭通道
        clientChannel.close();
    }

    @Test
    public void server() throws IOException {
        //1.获取通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        //2.设置非阻塞状态
        serverChannel.configureBlocking(false);
        //3.绑定连接
        serverChannel.bind(new InetSocketAddress(9898));
        //4.获取选择器
        Selector selector = Selector.open();
        //5.将通道注册到选择器上，并且指定“监听接收事件”
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        //6.轮询式的获取选择器上已经“准备就绪”的事件
        while (selector.select() > 0) {
            //7.获取当前选择器中所有注册的“选择建”（已经就绪的监听事件）
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                //8.获取准备“就绪”的事件
                SelectionKey sk = iterator.next();

                //9.判断具体是什么事件准备就绪
                if (sk.isAcceptable()) {
                    //10.如果“接收就绪”，获取客户端连接
                    SocketChannel clientChannel = serverChannel.accept();
                    //11.切换非阻塞模式
                    clientChannel.configureBlocking(false);
                    //12.将通道注册到选择器上
                    clientChannel.register(selector, SelectionKey.OP_READ);
                } else if (sk.isReadable()) {
                    //13.获取当前选择器上读数据通道
                    SocketChannel clientChannel = (SocketChannel) sk.channel();
                    //14.读取数据
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = clientChannel.read(buf)) != -1) {
                        buf.flip();
                        System.out.println(new String(buf.array(), 0, len));
                        buf.clear();
                    }
                }
                //15.取消选择建SelectionKey
                iterator.remove();
            }
        }
    }

}
